package com.xs.ahoi.hcxs.dao;

import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.xs.ahoi.hcxs.model.BookMark;
import com.xs.ahoi.hcxs.utils.DateUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * author: ahoi
 * date: 2018/6/21 13:28
 * description: 书签
 */
public class BookMarkDao {

    private static BookMarkDao instance;
    private static SQLiteDatabase db;

    private BookMarkDao() {
    }

    public static synchronized BookMarkDao getInstance() {
        if (db == null) {
            db = DBHelper.getInstance().getDb();
        }
        if (instance == null) {
            instance = new BookMarkDao();
        }
        return instance;
    }

    // 保存书签
    public void save(int bookId, int position, String content, String catalog) {
        String sql = "insert into " + DBHelper.TABLE_NAME_BOOK_MARK + " (book_id, position, content, catalog, create_time) values (?, ?, ?, ?, ?);";
        db.execSQL(sql, new Object[]{bookId, position, content, catalog, DateUtil.getTime()});
    }

    // 查询所有书签
    public List<BookMark> listAll(int bookId) {
        Cursor cursor = null;
        List<BookMark> list = new ArrayList<>();
        String sql = "select * from " + DBHelper.TABLE_NAME_BOOK_MARK + " where book_id = ? order by create_time desc ";
        try {
            cursor = db.rawQuery(sql, new String[]{bookId + ""});
            while (cursor.moveToNext()) {
                list.add(cursorToModel(cursor));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return list;
    }

    // 删除书签
    public void deleteById(int id) {
        String sql = "delete from " + DBHelper.TABLE_NAME_BOOK_MARK + " where id = " + id;
        db.execSQL(sql);
    }

    // 删除指定书的所有书签
    public void deleteByBookId(String bookId) {
        String sql = "delete from " + DBHelper.TABLE_NAME_BOOK_MARK + " where book_id in (" + bookId + ")";
        db.execSQL(sql);
    }

    private BookMark cursorToModel(Cursor cursor) {
        BookMark model = new BookMark();
        model.setId(cursor.getInt(0));
        model.setBookId(cursor.getInt(1));
        model.setPosition(cursor.getInt(2));
        model.setContent(cursor.getString(3));
        model.setCatalog(cursor.getString(4));
        model.setCreateTime(cursor.getLong(5));
        return model;
    }

}
